package com.jeesite.modules.rt.api;

import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.NumberUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.config.Result;
import com.jeesite.modules.ic.entity.IcCard;
import com.jeesite.modules.ic.entity.IcUser;
import com.jeesite.modules.ic.service.IcUserService;
import com.jeesite.modules.mo.dao.MoShouyiDao;
import com.jeesite.modules.mo.dao.MoUserDeviceDao;
import com.jeesite.modules.mo.entity.MoShouyi;
import com.jeesite.modules.mo.entity.MoUserDevice;
import com.jeesite.modules.mo.service.MoUserDeviceService;
import com.jeesite.modules.rt.dao.RtDeviceUpdownDao;
import com.jeesite.modules.rt.entity.*;
import com.jeesite.modules.rt.service.*;
import com.jeesite.modules.sys.utils.DictUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RestController
@RequestMapping("/app/api/rt")
//@RequestMapping("/api/rt")
public class ApiDeviceController extends BaseController {

    @Autowired
    private RtDeviceService rtDeviceService;
    @Autowired
    private MoUserDeviceService moUserDeviceService;
    @Autowired
    private RtGroupService rtGroupService;
    @Autowired
    private RtDevicePaoliangService rtDevicePaoliangService;
    @Autowired
    private RtDeviceUpdownService rtDeviceUpdownService;
    @Autowired
    private RtDeviceUpdownDao rtDeviceUpdownDao;
    @Autowired
    private RtDeviceLineService rtDeviceLineService;
    @Autowired
    private RtDeviceHardwareService rtDeviceHardwareService;
    @Autowired
    private MoShouyiDao moShouyiDao;
    @Autowired
    private MoUserDeviceDao moUserDeviceDao;
    @Autowired
    private IcUserService icUserService;
    @Autowired
    private RtDailiDeviceService rtDailiDeviceService;


    /**
     * 设备首页统计
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/deviceIndexTongji")
    public Result deviceIndexTongji(HttpServletRequest request, HttpServletResponse response){
        String user_id = getUserId(request);
        Map<String,Object> map = new HashMap<>();
        IcUser icUser = icUserService.get(user_id);
        MoUserDevice moUserDevice = new MoUserDevice();
        moUserDevice.setUserId(user_id);
        List<MoUserDevice> list = moUserDeviceService.findList(moUserDevice);
        //累计收益
        double zongShouyi = icUser.getSumIncome();
        //昨日收益
        double yesterShouji = moShouyiDao.shouyiSumByUser(user_id, 1, DateUtils.getDate("yyyy-MM-dd", -1, Calendar.DATE), null);

        //离线数
        int onLineNum = 0;
        //在线数
        int unLineNum = 0;


        for (int i = 0; i < list.size(); i++) {
            MoUserDevice moUserDevice1 = list.get(i);
            RtDevice device = moUserDevice1.getDevice();
            String online = device.getOnline();
            if("1".equals(online)){
                unLineNum++;
            }else{
                onLineNum++;
            }
        }
        //累计收益
        map.put("zongShouyi",zongShouyi);
        //昨日收益
        map.put("yesterShouji",yesterShouji);
        //设备总数
        map.put("sumCount",list.size());
        //在线数
        map.put("onLineNum",onLineNum);
        //离线数
        map.put("unLineNum",unLineNum);

        return Result.buildSuccessResult(map);

    }

    

    /**
     * 修改设备备注和分组
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/deviceUpdate")
    public Result deviceUpdate(MoUserDevice moUserDevice,HttpServletRequest request, HttpServletResponse response){
        moUserDeviceService.save(moUserDevice);
        return Result.buildSuccessResult();
    }

    /**
     * 删除设备
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/devicedel")
    public Result devicedel(MoUserDevice moUserDevice,HttpServletRequest request, HttpServletResponse response){
        moUserDeviceService.delete(moUserDevice);
        return Result.buildSuccessResult();
    }

    /**
     * 设备详情
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/deviceInfo")
    public Result deviceInfo(String sn,HttpServletRequest request, HttpServletResponse response){
        String user_id = getUserId(request);
        RtDevice deviceBySn = rtDeviceService.getDeviceBySn(sn);
        deviceBySn.setModel(DictUtils.getDictLabel("rt_model",deviceBySn.getModel(),""));
        MoUserDevice moUserDevice = moUserDeviceService.findBySn(sn);
        String groupId = moUserDevice.getGroupId();
        RtGroup rtGroup = rtGroupService.get(groupId);
        deviceBySn.setFenzuName(rtGroup.getName());
        moUserDevice.setDevice(deviceBySn);
        //跑量信息
        Map<String,Object> map = new HashMap<>();
        List<RtDeviceUpdown> upDownBySnList = rtDeviceUpdownDao.getUpDownBySnList(sn);
        List<String> shijian = new ArrayList<>();
        List<String> upList = new ArrayList<>();
        List<String> downList = new ArrayList<>();
        if(upDownBySnList.size()>0){
            for (int i = upDownBySnList.size()-1; i >= 0; i--) {
                RtDeviceUpdown rtDeviceUpdown = upDownBySnList.get(i);
                shijian.add(DateUtils.formatDate(rtDeviceUpdown.getWorkDate(),"HH:mm"));
                upList.add(rtDeviceUpdown.getUp()!=null?NumberUtils.formatDouble(Double.valueOf(rtDeviceUpdown.getUp())):"0.00");
                downList.add(rtDeviceUpdown.getDown()!=null?NumberUtils.formatDouble(Double.valueOf(rtDeviceUpdown.getDown())):"0.00");
            }
        }else{
            shijian = Arrays.asList(new String[]{"","","","","",""});
            upList = Arrays.asList(new String[]{"0","0","0","0","0","0"});
            downList = Arrays.asList(new String[]{"0","0","0","0","0","0"});
        }
        map.put("shijian",shijian);
        map.put("upList",upList);
        map.put("downList",downList);
        //网络信息
        RtDeviceLine rtDeviceLine = rtDeviceLineService.getDeviceLineBySn(sn);
        rtDeviceLine.setIspCode(DictUtils.getDictLabel("rt_isp_code",rtDeviceLine.getIspCode(),""));
        if(StringUtils.isNotEmpty(rtDeviceLine.getNat())){
            rtDeviceLine.setNat(DictUtils.getDictLabel("rt_nat",rtDeviceLine.getNat().trim(),""));
        }
        rtDeviceLine.setIsIpv6("0".equals(rtDeviceLine.getIsIpv6())?"否":"是");
        rtDeviceLine.setPingLoss(rtDeviceLine.getPingLoss()+"%");
        rtDeviceLine.setPingRtt(rtDeviceLine.getPingRtt()+"ms");
        moUserDevice.setRtDeviceLine(rtDeviceLine);
        //设备信息
        RtDeviceHardware rtDeviceHardware = rtDeviceHardwareService.findOneBySn(sn);
        if(rtDeviceHardware!=null){
            double xtTotal = Double.valueOf(rtDeviceHardware.getXtTotal()!=null?rtDeviceHardware.getXtTotal():"0");
            double xtUsed = Double.valueOf(rtDeviceHardware.getXtUsed()!=null?rtDeviceHardware.getXtUsed():"0");
            double total = Double.valueOf(rtDeviceHardware.getTotal()!=null?rtDeviceHardware.getTotal():"0");
            double used = Double.valueOf(rtDeviceHardware.getUsed()!=null?rtDeviceHardware.getUsed():"0");
            double zongTotal = NumberUtils.add(xtTotal, total);
            double zongUsed = NumberUtils.add(xtUsed, used);
            double xtBaifenbi =0;
            if(xtTotal!=0){
                xtBaifenbi = NumberUtils.div(xtUsed * 100, xtTotal);
            }
            double baifenbi = 0;
            if(total!=0){
                baifenbi = NumberUtils.div(used * 100, total);
            }
            map.put("zongTotal",zongTotal);
            map.put("zongUsed",zongUsed);
            map.put("xtBaifenbi",xtBaifenbi);
            map.put("baifenbi",baifenbi);
        }

        moUserDevice.setMap(map);
        moUserDevice.setRtDeviceHardware(rtDeviceHardware);
        return Result.buildSuccessResult(moUserDevice);
    }

    /**
     * 设备列表
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/deviceList")
    public Result deviceList(@RequestBody MoUserDevice moUserDevice, HttpServletRequest request, HttpServletResponse response){
        String user_id = getUserId(request);
        RtGroup rtGroup = new RtGroup();
        rtGroup.setUserId(user_id);
        Map<String,String> map = new HashMap<>();
        List<RtGroup> list1 = rtGroupService.findList(rtGroup);
        for (RtGroup rtGroup1 : list1) {
            map.put(rtGroup1.getId(),rtGroup1.getName());
        }
        moUserDevice.setUserId(user_id);
        if(moUserDevice.getDevice()==null){
            moUserDevice.setDevice(new RtDevice());
        }
        List<MoUserDevice> list = moUserDeviceService.findList(moUserDevice);
        for (MoUserDevice moUserDevice1 : list) {
            moUserDevice1.setGroupId(map.get(moUserDevice1.getGroupId()));
            String sn = moUserDevice1.getSn();
            moUserDevice1.getDevice().setIspStr(DictUtils.getDictLabel("rt_isp_code",moUserDevice1.getDevice().getIspCode().toString(),"其他"));
            if(StringUtils.isNotEmpty(moUserDevice1.getDevice().getNat())){
                moUserDevice1.getDevice().setNat(DictUtils.getDictLabel("rt_nat",moUserDevice1.getDevice().getNat().toString().trim(),"其他"));
            }
            //判断昨天是否有收益
            double v = moShouyiDao.shouyiSumByUser(moUserDevice1.getUserId(), 1, DateUtils.getDate("yyyy-MM-dd", -1, Calendar.DATE), sn);
            moUserDevice1.setYesterIcome(v);
        }
        return Result.buildSuccessResult(list);
    }

    /**
     * 添加设备
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/addDevice")
    public Result addDevice(String sn, HttpServletRequest request, HttpServletResponse response){
        String user_id = getUserId(request);
        MoUserDevice bySn = moUserDeviceService.findBySn(sn);
        if(bySn != null){
            return Result.buildFailureResult("此设备已被绑定");
        }
        MoUserDevice moUserDevice = new MoUserDevice();
        moUserDevice.setSn(sn);
        moUserDevice.setUserId(user_id);
        RtGroup rtGroup = new RtGroup();
        rtGroup.setUserId(user_id);
        rtGroup.setName("默认分组");
        List<RtGroup> list = rtGroupService.findList(rtGroup);
        if(list.size()>0){
            moUserDevice.setGroupId(list.get(0).getId());
        }
        RtDevice deviceBySn = rtDeviceService.getDeviceBySn(sn);
        if(deviceBySn==null){
            return Result.buildFailureResult("未识别到设备信息,请检査后重试");
        }
        moUserDevice.setDeviceId(deviceBySn.getId());
        moUserDeviceService.save(moUserDevice);

        //绑定用户上下级关系
        IcUser icUser = icUserService.get(user_id);
        String parentUserId = icUser.getParentUserId();
        if(StringUtils.isEmpty(parentUserId)){
            RtDailiDevice oneBySn = rtDailiDeviceService.getOneBySn(sn);
            if(oneBySn!=null){
                String dailishangId = oneBySn.getDailishangId();
                if(StringUtils.isNotEmpty(dailishangId)){
                    icUser.setParentUserId(dailishangId);
                    icUserService.save(icUser);
                    oneBySn.setUserId(user_id);
                    rtDailiDeviceService.save(oneBySn);
                }
            }
        }

        return Result.buildSuccessResult();
    }

    /**
     * 保存分组
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/saveGroup")
    public Result saveGroup(RtGroup rtGroup, HttpServletRequest request, HttpServletResponse response){
        String user_id = getUserId(request);
        rtGroup.setName(rtGroup.getName());
        rtGroup.setUserId(user_id);
        List<RtGroup> list = rtGroupService.findList(rtGroup);
        if(list.size() > 0){
            RtGroup rtGroup1 = list.get(0);
            if(rtGroup.getId()!=null){
                if(!rtGroup1.getId().equals(rtGroup.getId())){
                    return Result.buildFailureResult("分组已经存在，不可重复添加");
                }
            }else{
                return Result.buildFailureResult("分组已经存在，不可重复添加");
            }
        }
        rtGroupService.save(rtGroup);
        return Result.buildSuccessResult();
    }

    /**
     * 删除分组
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/groupList")
    public Result groupList(String id, HttpServletRequest request, HttpServletResponse response){
        String user_id = getUserId(request);
        RtGroup rtGroup = new RtGroup();
        rtGroup.setUserId(user_id);
        List<RtGroup> list = rtGroupService.findList(rtGroup);
        return Result.buildSuccessResult(list);
    }

    /**
     * 删除分组
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/delGroup")
    public Result delGroup(RtGroup rtGroup, HttpServletRequest request, HttpServletResponse response){
        MoUserDevice moUserDevice = new MoUserDevice();
        moUserDevice.setGroupId(rtGroup.getId());
        if(moUserDeviceService.findCount(moUserDevice)>0){
            return Result.buildFailureResult("该分组下还有设备，不可删除。");
        }
        rtGroupService.delete(rtGroup);
        return Result.buildSuccessResult();
    }

    public String getUserId(HttpServletRequest request){
        Object user_id = request.getAttribute("user_id");
        if(user_id!=null){
            return user_id.toString();
        }
        return request.getParameter("userId");
    }
}
